import React, { useState } from 'react'
import { Button } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { createFileChunk } from './utils';
// 关键点
// 1. 获取文件，利用Blob.prototype.slice进行分片
// 2. 对每一个分片使用FormData进行数据整理，再分别发送出去
// 3. 使用Promise.all将多个Promise实例，包装成一个新的Promise实例
//    并发处理
export default function UpBigload() {

  const [containFile, setFile] = useState(null);
  const handleFileChange = (ev) => {
    const [file] = ev.target.files;
    if (!file) return;
    setFile(file);
  }


  async function handleUpload() {
    if (!containFile) return;
    const fileChunkList = createFileChunk(containFile)
    const data = fileChunkList.map(({ file }, index) => ({
      chunk: file,
      hash: containFile.name + '-' + index,
    }))
    await uploadChunks(data);
  }
  async function uploadChunks(data) {
    const requestList = data
      .map(({ chunk, hash }) => {
        const formData = new FormData();
        formData.append("chunk", chunk);
        formData.append("hash", hash);
        formData.append("filename", containFile?.name);
        return { formData };
      })
      .map(async ({ formData }) =>
        this.request({
          url: "http://localhost:3000",
          data: formData
        })
      );
    await Promise.all(requestList); // 并发切片
    // 合并切片
    await mergeRequest();
  }
  async function mergeRequest() {

  }
  return (
    <div>
      <input type='file' onChange={handleFileChange} />
      <Button type="primary" shape="circle" icon={<DownloadOutlined />} size='large' />
    </div>
  )
}
